//
//  JMTenLocationManager.m
//  NewiOSProject
//
//  Created by apple on 2023/9/27.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMTenLocationManager.h"
#import <AVFoundation/AVFoundation.h>
#import <EventKit/EventKit.h>
#import <CoreLocation/CoreLocation.h>
#import <Contacts/Contacts.h>
#import <UserNotifications/UserNotifications.h>
#import <AdSupport/AdSupport.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@interface JMTenLocationManager () <CLLocationManagerDelegate>
/**请求定位权限结果类*/
@property (nonatomic, copy) void (^locationAuthBlock) (BOOL granted, CLAuthorizationStatus state);
/**系统定位*/
@property (nonatomic, strong) CLLocationManager *sys_locationManager;
@end

static JMTenLocationManager *_locationManager;

@implementation JMTenLocationManager

/**构造方法*/
+(instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_locationManager == nil) {
            _locationManager = [super allocWithZone:zone];
        }
    });
    return _locationManager;
}

/**单例方法*/
+(instancetype)shareManager {
    return [[self alloc] init];
}

/**1.唤起定位权限请求*/
-(void)ten_requestLocationRequest:(void (^)(BOOL, CLAuthorizationStatus))block {
    self.locationAuthBlock = block;
    [self.sys_locationManager requestWhenInUseAuthorization];
}

#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (self.locationAuthBlock) {
        if (status==kCLAuthorizationStatusNotDetermined
            ||status==kCLAuthorizationStatusRestricted
            || status==kCLAuthorizationStatusDenied) {
            self.locationAuthBlock(NO, status);
            
        }else{
            self.locationAuthBlock(YES, status);
            
        }
    }
}

#pragma mark - lazy getter
-(CLLocationManager *)sys_locationManager {
    if (!_sys_locationManager) {
        _sys_locationManager = [[CLLocationManager alloc]init];
        _sys_locationManager.delegate = self;
    }
    return _sys_locationManager;
}

- (CLAuthorizationStatus)authorizationStatus {
    if (@available(iOS 14, *)) {
        return self.sys_locationManager.authorizationStatus;
    }else {
        return [CLLocationManager authorizationStatus];
    }
}

//.地址
-(TenAuthorizationStatus)locationStatus {
    if (![CLLocationManager locationServicesEnabled]) {
        //手机定位权限未开启(针对全部应用)
        return TenAuthorizationStatusRestricted;
    }
    TenAuthorizationStatus status;
    switch ([CLLocationManager authorizationStatus]) {
        case kCLAuthorizationStatusNotDetermined:
            status = TenAuthorizationStatusNotDetermined;
            break;
        case kCLAuthorizationStatusDenied:
            status = TenAuthorizationStatusDenied;
            break;
        case kCLAuthorizationStatusRestricted:
            status = TenAuthorizationStatusRestricted;
            break;
        default:
            status = TenAuthorizationStatusAuthorized;
            break;
    }
    return status;
}
//5.联系人
-(void)applyContact:(void (^)(BOOL granted, TenAuthorizationStatus status))block{
    if (@available(iOS 9.0, *)) {
        [[[CNContactStore alloc] init] requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            block(granted,[self addressBookStatus]);
        }];
    }else {
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            block(granted,[self addressBookStatus]);
        });
    }
}

-(void)showContactAuthAlert:(void(^)())completion{
    delayOperation(0, ^{
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"Advertencia" message:@"Sus permisos de libreta de direcciones están cerrados. para acceder a la libreta de direcciones, abra los permisos de libreta de direcciones aplicados en la configuración." preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancelación" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            completion();
        }];
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"Determinar" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alertC addAction:cancel];
        [alertC addAction:confirm];
        
        [UIWindow.jm_currentViewController presentViewController:alertC animated:YES completion:^{
           
        }];
    });
}
-(void)showCustomAuthAlert{
    [JMPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-50, 200)) Title:@"Advertencia" subTitle:@"Sus permisos de libreta de direcciones están cerrados. para acceder a la libreta de direcciones, abra los permisos de libreta de direcciones aplicados en la configuración." BottomBtns:@[@"Cancelación",@"Determinar"] Position:(JMPublicAlertViewPositionCenter) btnDirection:(JMPublicAlertViewButtonDirectionHor) btnActionBlock:^(NSInteger btnTag) {
        if (btnTag==1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }];
}
-(TenAuthorizationStatus)addressBookStatus {
    TenAuthorizationStatus status;
    if (@available(iOS 9.0, *)) {
        switch ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]) {
            case CNAuthorizationStatusAuthorized:
                status = TenAuthorizationStatusAuthorized;
                break;
            case CNAuthorizationStatusNotDetermined:
                status = TenAuthorizationStatusNotDetermined;
                break;
            case CNAuthorizationStatusRestricted:
                status = TenAuthorizationStatusRestricted;
                break;
            default:
                status = TenAuthorizationStatusDenied;
                break;
        }
    } else {
        switch (ABAddressBookGetAuthorizationStatus()) {
            case kABAuthorizationStatusAuthorized:
                status = TenAuthorizationStatusAuthorized;
                break;
            case kABAuthorizationStatusNotDetermined:
                status = TenAuthorizationStatusNotDetermined;
                break;
            default:
                status = TenAuthorizationStatusDenied;
                break;
        }
    }
    return status;
}

//广告追踪
-(void)applyADSupport:(void (^)(BOOL granted, TenAuthorizationStatus status))block{
    if ([ASIdentifierManager.sharedManager isAdvertisingTrackingEnabled]) {
        NSString * idfa = [ASIdentifierManager.sharedManager advertisingIdentifier].UUIDString;
    }else{
        [ATTrackingManager  requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                block(YES,[self addAuthStatus]);
            }else{
                block(NO,[self addAuthStatus]);
            }
        }];
    }
}
-(TenAuthorizationStatus)addAuthStatus{
    if (@available(iOS 14, *)) {
        ATTrackingManagerAuthorizationStatus status = ATTrackingManager.trackingAuthorizationStatus;
        switch (status) {
            case ATTrackingManagerAuthorizationStatusDenied:
                NSLog(@"用户拒绝");
                return TenAuthorizationStatusDenied;
                break;
            case ATTrackingManagerAuthorizationStatusAuthorized:
                NSLog(@"用户允许");
                return TenAuthorizationStatusAuthorized;
                break;
            case ATTrackingManagerAuthorizationStatusNotDetermined:
                NSLog(@"用户为做选择或未弹窗");
                return TenAuthorizationStatusNotDetermined;
                break;
            default:
                return TenAuthorizationStatusDenied;
                break;
        }
    } else {
        if ([ASIdentifierManager.sharedManager isAdvertisingTrackingEnabled]) {
            return TenAuthorizationStatusAuthorized;
            
        }else {
            return TenAuthorizationStatusDenied;
        }
    }
}

//2.相机
-(void)applyCamera:(void (^)(BOOL granted, TenAuthorizationStatus status))block{
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        if (granted) {
            block(granted,TenAuthorizationStatusAuthorized);
        }else{
            block(granted,TenAuthorizationStatusDenied);
        }
    }];
}

-(TenAuthorizationStatus)cameraStatue {
    TenAuthorizationStatus status;
    switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) {
        case AVAuthorizationStatusAuthorized:
            status = TenAuthorizationStatusAuthorized;
            break;
        case AVAuthorizationStatusNotDetermined:
            status = TenAuthorizationStatusNotDetermined;
            break;
        case AVAuthorizationStatusRestricted:
            status = TenAuthorizationStatusRestricted;
            break;
        default:
            status = TenAuthorizationStatusDenied;
            break;
    }
    return status;
}




//3.相册
-(void)applyPhoto:(void (^)(BOOL granted, TenAuthorizationStatus status))block{
//    if (@available(iOS 14, *)) {
//        [PHPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:^(PHAuthorizationStatus status) {
//            if (self.locationAuthBlock) {
//                if (status==PHAuthorizationStatusNotDetermined
//                    ||status==PHAuthorizationStatusRestricted
//                    || status==PHAuthorizationStatusDenied) {
//                    self.locationAuthBlock(NO, status);
//                }else{
//                    self.locationAuthBlock(YES, status);
//                }
//            }
//        }];
//    } else {
//        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
//            if (status==PHAuthorizationStatusNotDetermined
//                ||status==PHAuthorizationStatusRestricted
//                || status==PHAuthorizationStatusDenied) {
//                self.locationAuthBlock(NO, status);
//            }else{
//                self.locationAuthBlock(YES, status);
//            }
//        }];
//    }
}
-(TenAuthorizationStatus)photoLibraryStatus {
    TenAuthorizationStatus status;
    //    EHIAuthorizationStatus status;
    
//    if (@available(iOS 14, *)) {
//        switch ([PHPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite]) {
//            case PHAuthorizationStatusAuthorized:
//                //全部
//                status = TenAuthorizationStatusAuthorized;
//                break;
//            case PHAuthorizationStatusLimited:
//                //部分
//                status = TenAuthorizationStatusAuthorized;
//                break;
//            case PHAuthorizationStatusNotDetermined:
//                status = TenAuthorizationStatusNotDetermined;
//                break;
//            case PHAuthorizationStatusRestricted:
//                status = TenAuthorizationStatusRestricted;
//                break;
//            default:
//                status = TenAuthorizationStatusDenied;
//                break;
//        }
//    }else {
//        switch ([PHPhotoLibrary authorizationStatus]) {
//            case PHAuthorizationStatusAuthorized:
//                status = TenAuthorizationStatusAuthorized;
//                break;
//            case PHAuthorizationStatusNotDetermined:
//                status = TenAuthorizationStatusNotDetermined;
//                break;
//            case PHAuthorizationStatusRestricted:
//                status = TenAuthorizationStatusRestricted;
//                break;
//            default:
//                status = TenAuthorizationStatusDenied;
//                break;
//        }
//    }
    return status;
}


//4.日历 申请
-(void)applyCalender:(void (^)(BOOL granted, TenAuthorizationStatus status))block{
    [[[EKEventStore alloc] init] requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError * _Nullable error) {
        
    }];
}

-(TenAuthorizationStatus)calendarStatus {
    TenAuthorizationStatus status;
    switch ([EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent]) {
        case EKAuthorizationStatusAuthorized:
            status = TenAuthorizationStatusAuthorized;
            break;
        case EKAuthorizationStatusNotDetermined:
            status = TenAuthorizationStatusNotDetermined;
            break;
        case EKAuthorizationStatusRestricted:
            status = TenAuthorizationStatusRestricted;
            break;
        default:
            status = TenAuthorizationStatusDenied;
            break;
    }
    return status;
}



//6.提醒
-(void)applyRemind:(void (^)(BOOL granted, TenAuthorizationStatus status))block{

    if (@available(iOS 17.0, *)) {
 
        [[[EKEventStore alloc]init] requestFullAccessToRemindersWithCompletion:^(BOOL granted, NSError * _Nullable error) {
            block(granted,[self remindStatus]);
        }];

    }else{
        [[[EKEventStore alloc] init] requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError * _Nullable error) {
            block(granted,[self remindStatus]);
        }];
    }
   
}
-(TenAuthorizationStatus)remindStatus {
    TenAuthorizationStatus status;
    switch ([EKEventStore authorizationStatusForEntityType:EKEntityTypeReminder]) {
        case EKAuthorizationStatusAuthorized:
            status = TenAuthorizationStatusAuthorized;
            break;
        case EKAuthorizationStatusNotDetermined:
            status = TenAuthorizationStatusNotDetermined;
            break;
        case EKAuthorizationStatusRestricted:
            status = TenAuthorizationStatusRestricted;
            break;
        default:
            status = TenAuthorizationStatusDenied;
            break;
    }
    return status;
}

//7.推送权限
-(TenAuthorizationStatus)pushStatus:(void (^)(BOOL, TenAuthorizationStatus))block {
    if (@available(iOS 10.0, *)) {
        dispatch_semaphore_t singal = dispatch_semaphore_create(0);//创建信号量
        __block TenAuthorizationStatus status;
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            switch (settings.authorizationStatus) {
                case UNAuthorizationStatusDenied:
                    status = TenAuthorizationStatusDenied;
                    break;
                case UNAuthorizationStatusNotDetermined:
                    status = TenAuthorizationStatusNotDetermined;
                    break;
                default:
                    status = TenAuthorizationStatusAuthorized;
                    break;
            }
            dispatch_semaphore_signal(singal);//赋值完成发送信号
        }];
        dispatch_semaphore_wait(singal, DISPATCH_TIME_FOREVER);//等待信号
        return status;
    }
    return ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone) ? TenAuthorizationStatusDenied : TenAuthorizationStatusAuthorized;
}
-(void)applyPush{
    if (@available(iOS 10.0, *)) {
      [[UNUserNotificationCenter currentNotificationCenter]requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        
      }];
    }else {
      //iOS10之前，系统对于申请推送权限没有具体的API，只有设置NotificationSettings时，会自动请求权限
      UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge categories:nil];
      [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    }
}
//8.麦克风 权限请求
-(void)applyMicrophone:(void (^)(BOOL granted, TenAuthorizationStatus status))block{
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {

    }];
}
//权限获取
-(TenAuthorizationStatus)microphoneStatus {
    TenAuthorizationStatus status;
    switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
        case AVAuthorizationStatusAuthorized:
            status = TenAuthorizationStatusAuthorized;
            break;
        case AVAuthorizationStatusNotDetermined:
            status = TenAuthorizationStatusNotDetermined;
            break;
        case AVAuthorizationStatusRestricted:
            status = TenAuthorizationStatusRestricted;
            break;
        default:
            status = TenAuthorizationStatusDenied;
            break;
    }
    return status;
}
@end
